package com.promise.jokerdream.work.penguin

import com.promise.jokerdream.database.entity.OtherGameConfigEntity
import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 画卷迷踪工作
class ScrollDungeonWork(
    private val config: OtherGameConfigEntity,
    uin: String
): BaseWork(uin) {

    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }

    override val name: String
        get() = "画卷迷踪"

    override suspend fun executeWork(): WorkResult {
        return try {
            // 查询画卷迷踪信息
            val queryResult = gameApi.queryScrollDungeon()
            
            queryResult.fold(
                onSuccess = { response ->
                    // 检查是否有可用次数（免费次数或付费次数）
                    if (response.freeTimes > 0 || response.payTimes > 0) {
                        // 有可用次数，执行挑战
                        var shouldContinue = true
                        while (shouldContinue) {
                            val fightResult = gameApi.fightScrollDungeon()
                            fightResult.fold(
                                onSuccess = { fightResponse ->
                                    historyManager.addHistory(name, fightResponse.getDescription())
                                },
                                onFailure = { exception ->
                                    historyManager.addHistory(name, exception.message)
                                    // 发生错误时停止挑战
                                    shouldContinue = false
                                }
                            )
                        }
                    }
                    // 没有可用次数时直接返回成功，不执行挑战
                    WorkResult.Success
                },
                onFailure = { exception ->
                    historyManager.addHistory(name, exception.message)
                    WorkResult.Failure(exception, exception.message)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
}